package a66weding.com.jiehuntong.pager;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.bumptech.glide.Glide;

import org.xutils.common.util.DensityUtil;
import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import a66weding.com.jiehuntong.MainActivity;
import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.CategorySearchActivity;
import a66weding.com.jiehuntong.activity.ElectronicInvitationHomeActivity;
import a66weding.com.jiehuntong.activity.LoginActivity;
import a66weding.com.jiehuntong.activity.SearchCityActivity;
import a66weding.com.jiehuntong.activity.WebViewActvity;
import a66weding.com.jiehuntong.activity.home.HomeFindbusinshopActivity;
import a66weding.com.jiehuntong.activity.home.HomeWedShoppingActivity;
import a66weding.com.jiehuntong.activity.home.hotel.hotelnew.HomeHotelActivity2;
import a66weding.com.jiehuntong.activity.home.hotel.shop.HomeProductdetailActivity;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.CancelCollectBean;
import a66weding.com.jiehuntong.beans.CateguryGridViewBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HomeBotomListBean;
import a66weding.com.jiehuntong.beans.HomeGifPathBean;
import a66weding.com.jiehuntong.beans.HomeHeaderLooperBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MeShoppingCartDeleteBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.User;
import a66weding.com.jiehuntong.common.api.Url;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.FileUtil;
import a66weding.com.jiehuntong.common.utils.ImageOptionsUtil;
import a66weding.com.jiehuntong.common.utils.LogUtil;
import a66weding.com.jiehuntong.common.utils.Utils;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;
import a66weding.com.jiehuntong.view.BaseViewPager;
import a66weding.com.jiehuntong.view.ConfirmLoginDialog;
import a66weding.com.jiehuntong.view.EditTextWithAutoClear;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

/**
 * 首页
 * Created by y on 2016/5/17.
 */
public class HomePager extends BasePager implements View.OnClickListener, OnNetResultListener {
    private MainActivity mMainActivity;
    private LinearLayout mCityFindLay;
    private TextView mCitynameTv;
    private BaseViewPager mTopViewPager;
    private LinearLayout mProgress;
    private LinearLayout mNoDataLay;
    private ImageView mGotopIv;
    private View mHomeView;
    private ListView mListView;
    private XRefreshView mRefreshView;
    private EditTextWithAutoClear mEditView;
    private LinearLayout mTopLooperLay;
    private ImageView mRedpoint;
    //找商家
    private LinearLayout mFindshopLay;
    private LinearLayout mWedGuideLay;
    private LinearLayout mInvitationLay;
    private LinearLayout mFreeExpLay;
    //酒店预订
    private RelativeLayout mHotelLay;
    //婚品购置
    private RelativeLayout mWedShoppingLay;
    private RelativeLayout mWedPhotoLay;
    private RelativeLayout mCelebrateLay;
    private RelativeLayout mTakePhotoLay;
    private HomeListAdapter mHomeAdapter;
    public static final int TOPVIEWSCROLL = 1;
    private static final int MSG_INFRESH = 6;
    private static int pageIndex = 1;
    private int mLastLoadIndex;
    private List<ImageView> mPointList;
    private int maxCount = Integer.MAX_VALUE;
    private ImgAdapter imgAdapter;
    private int distance = DensityUtil.dip2px(6) * 2;//两个普通点之间的间距
    //红点要移动的坐标
    private int px = DensityUtil.dip2px(6);
    private List<HomeHeaderLooperBean.DataBean> looperDataList;
    private int i_id;
    private boolean islogin;
    private List<HomeBotomListBean.DataBean> bottomList;
    private CateguryGridViewBean categuryData;
    private String cityName = "北京";
    private final int DIALOG = 10;
    private MyDialog myDialog;
    private int mCurrentItem;
    private ImageView promotionIv;

    public HomePager(Activity activity) {
        super(activity);
    }

    private boolean isShowError;
    private GifImageView gifImageView;
    private RelativeLayout ad_banner_rl;
    private HomeGifPathBean.DataBean homeGifBean;
    public boolean isFirstRequest = true;
    public final int REQUEST_LOGIN_CODE = 1000;
    public int tempI_Id;
    public int tempI_Business;
    public int tempPosition;

    @Override
    protected View getView() {
        isFirstRequest = true;
        this.mMainActivity = (MainActivity) mActivity;
        mHomeView = View.inflate(mActivity, R.layout.pager_home, null);
        mProgress = (LinearLayout) mHomeView.findViewById(R.id.loading_homepage);
        mNoDataLay = (LinearLayout) mHomeView.findViewById(R.id.lay_netfailer);
        mRefreshView = (XRefreshView) mHomeView.findViewById(R.id.xrefreshview_home);
        initRefreshView();
        initView(mHomeView);
        return mHomeView;
    }

    private void initView(View view) {
        mListView = (ListView) view.findViewById(R.id.lview_pager_home);
        View headView = View.inflate(mActivity, R.layout.item_home_headview, null);
        mListView.addHeaderView(headView);
        gifImageView = (GifImageView) headView.findViewById(R.id.gif_imageview);
        // 动态为gifImageView设宽高
        // 获取屏幕高宽
        int windowsWith = Utils.getScreenWidth(mMainActivity);
        ad_banner_rl = (RelativeLayout) view.findViewById(R.id.ad_banner_rl);
        if (windowsWith > 0) {
            // 动态改变布局
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    (int) (windowsWith * 2.0 / 3));
            ad_banner_rl.setLayoutParams(params);
        }
        gifImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (homeGifBean != null && homeGifBean.getAddressUrl() != null) {
                    Intent intent = new Intent(mMainActivity, WebViewActvity.class);
                    intent.putExtra("urlPath", homeGifBean.getAddressUrl());
                    intent.putExtra("title", "幸福直通车");
                    intent.putExtra("share", false);
                    mMainActivity.startActivity(intent);
                } else {
                    Toast.makeText(mActivity, "未能获取到链接地址", Toast.LENGTH_SHORT).show();
                }
            }
        });

        mGotopIv = (ImageView) view.findViewById(R.id.gotop_btn);
        mEditView = (EditTextWithAutoClear) view.findViewById(R.id.etview_homeheader_search);
        mTopViewPager = (BaseViewPager) view.findViewById(R.id.vpager_homepager_loopview);
        mTopLooperLay = (LinearLayout) view.findViewById(R.id.llay_homeitem_toppoint);
        mRedpoint = (ImageView) view.findViewById(R.id.iv_guide_redpoint);
        mCityFindLay = (LinearLayout) view.findViewById(R.id.hometop_lay);
        mCitynameTv = (TextView) view.findViewById(R.id.tv_cityname);
        mFindshopLay = (LinearLayout) view.findViewById(R.id.llay_home_findshop);
        mWedGuideLay = (LinearLayout) view.findViewById(R.id.llay_home_wedguid);
        mInvitationLay = (LinearLayout) view.findViewById(R.id.llay_home_Einvitation);
        mFreeExpLay = (LinearLayout) view.findViewById(R.id.llay_home_freeExp);
        mHotelLay = (RelativeLayout) view.findViewById(R.id.rlay_home_hotel);
        mWedShoppingLay = (RelativeLayout) view.findViewById(R.id.rlay_home_wedshopping);
        mWedPhotoLay = (RelativeLayout) view.findViewById(R.id.rlay_home_wedphoto);
        mCelebrateLay = (RelativeLayout) view.findViewById(R.id.rlay_home_celebrate);
        mTakePhotoLay = (RelativeLayout) view.findViewById(R.id.rlay_home_takephoto);
        promotionIv = (ImageView) view.findViewById(R.id.iv_homepage_topicom);
        mCityFindLay.setVisibility(View.GONE);
        mNoDataLay.setOnClickListener(this);
        mEditView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    ((InputMethodManager) mEditView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(
                                    mMainActivity.getCurrentFocus().getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    //跳转activity
                    Intent intent = new Intent();
                    intent.setClass(mMainActivity, CategorySearchActivity.class);
                    String searchStr = mEditView.getText().toString();
                    if (searchStr.trim().isEmpty()) {
                        Toast.makeText(mActivity, "请输入搜索内容", Toast.LENGTH_SHORT).show();
                        return false;
                    } else if (searchStr.contains(" ")) {
                        Toast.makeText(mActivity, "请不要输入空格", Toast.LENGTH_SHORT).show();
                        return false;
                    } else {
                        if (!TextUtils.isEmpty(searchStr)) {
                            intent.putExtra("searchinfo", searchStr);
                        }
                        mMainActivity.startActivity(intent);
                        mEditView.setText("");
                        return true;
                    }
                }
                if (event.getAction() == KeyEvent.KEYCODE_BACK) {
                }
                return false;
            }
        });
        mCityFindLay.setOnClickListener(this);
        mFindshopLay.setOnClickListener(this);
        mWedGuideLay.setOnClickListener(this);
        mInvitationLay.setOnClickListener(this);
        mFreeExpLay.setOnClickListener(this);
        mHotelLay.setOnClickListener(this);
        mWedShoppingLay.setOnClickListener(this);
        mWedPhotoLay.setOnClickListener(this);
        mCelebrateLay.setOnClickListener(this);
        mTakePhotoLay.setOnClickListener(this);
        promotionIv.setOnClickListener(this);
        mGotopIv.setOnClickListener(this);

    }

    private void saveGifPic(final String urlPic) {
        String namaPic = urlPic.hashCode() + ".gif";
        File fileDir = FileUtil.getImgFile(mMainActivity);
        final File file = new File(fileDir, namaPic);
        if (file.exists()) {
            // 设置控件与图片等比例
            int windowsWith = Utils.getScreenWidth(mMainActivity);
            Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
            try {
                int picWidth = bm.getWidth();
                int picHeight = bm.getHeight();
                if (windowsWith > 0 && picWidth > 0 && picHeight > 0) {
                    // 动态改变布局
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            (int) (windowsWith * 1.0 * picHeight / picWidth));
                    gifImageView.setLayoutParams(params);
                }
                // 将gif图资源转化为GifDrawable
                GifDrawable gifDrawable = null;
                gifDrawable = new GifDrawable(file);
                // gif1加载一个动态图gif
                gifImageView.setImageDrawable(gifDrawable);
            } catch (IOException e) {
                e.printStackTrace();
                handler.sendEmptyMessage(1);
            }
        } else {
            //下载
            new Thread(new Runnable() {
                @Override
                public void run() {
                    InputStream inputStream = null;
                    OutputStream output = null;
                    try {
                        URL url = new URL(urlPic);
                        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                        inputStream = urlConn.getInputStream();
                        output = new FileOutputStream(file);
                        byte buffer[] = new byte[1024];
                        int len = 0;
                        //如果下载成功就开往SD卡里些数据
                        while ((len = inputStream.read(buffer)) != -1) {
                            output.write(buffer, 0, len);
                        }
                        output.flush();
                        Message mess = handler.obtainMessage(0);
                        mess.obj = file;
                        handler.sendMessage(mess);
                    } catch (Exception e) {
                        e.printStackTrace();
                        handler.sendEmptyMessage(1);
                    } finally {
                        try {
                            if (inputStream != null) {
                                inputStream.close();
                            }
                            if (output != null) {
                                output.close();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    GifDrawable gifDrawable = null;
                    File file = null;
                    if (msg.obj instanceof File) {
                        file = (File) msg.obj;
                    }
                    // 设置控件与图片等比例
                    int windowsWith = Utils.getScreenWidth(mMainActivity);
                    try {
                        Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
                        int picWidth = bm.getWidth();
                        int picHeight = bm.getHeight();
                        if (windowsWith > 0 && picWidth > 0 && picHeight > 0) {
                            // 动态改变布局
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.MATCH_PARENT,
                                    (int) (windowsWith * 1.0 * picHeight / picWidth));
                            gifImageView.setLayoutParams(params);
                        }
                        gifDrawable = new GifDrawable(file);
                        // gif1加载一个动态图gif
                        gifImageView.setImageDrawable(gifDrawable);
                    } catch (IOException e) {
                        e.printStackTrace();
                        handler.sendEmptyMessage(1);
                    }
                    break;
                case 1:
                    gifImageView.setVisibility(View.GONE);
                    break;
            }
        }
    };

    /**
     * 页面加载后调用的方法, 在此处请求数据并显示
     */
    @Override
    public void initData() {
        islogin = ((GlobalApplication) mMainActivity.getApplication()).isLogin();
        if (islogin) {
            User user = DataWareHourse.getInstance().getmUser();
            if (user != null) {
                i_id = user.getData().get(0).getI_Id();
            }
        }
        getData();
    }

    /**
     * 初始化界面数据
     */
    private void getData() {
        //顶部的轮播广告
        String headUrl = Url.HOMEPAGERHEADLOOPER;
        HttpRequestBean headerRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, headUrl,
                this, HomeHeaderLooperBean.class, RequestCode.HOMEPAGERHEADLOOPER);
        HttpHandleUtil.executeCommonGet(mMainActivity, headerRequestBean);
        //分页加载的
        getDataFromNet(1);
        //Gif图片
        loadGifPath();
        //婚品购置
        getCatagryDataFromNet();
    }

    /**
     * 分页加载数据
     */
    private void getDataFromNet(int pageIndex) {
        String bottomListUrl = Url.HOMEPAGERBOTTOM;
        bottomListUrl += "pageIndex=" + pageIndex + "&memberID=" + i_id;
        HttpRequestBean bottomListRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, bottomListUrl,
                this, HomeBotomListBean.class, RequestCode.HOMEPAGERBOTTOM);
        HttpHandleUtil.executeCommonGet(mMainActivity, bottomListRequestBean);
    }

    /**
     * 婚品购置的数据
     */
    private void getCatagryDataFromNet() {
        String url = Url.CATEGURYGRIDVIEW;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, url,
                this, CateguryGridViewBean.class, RequestCode.CATEGURY);
        HttpHandleUtil.executeCommonGet(mActivity, httpRequestBean);
    }

    /**
     * 获取gif图片地址
     */
    private void loadGifPath() {
        String url = Url.GETHOMEGIFPATH;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, url,
                this, HomeGifPathBean.class, "");
        HttpHandleUtil.executeCommonGet(mActivity, httpRequestBean);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.hometop_lay:
                Intent intent = new Intent(mMainActivity, SearchCityActivity.class);
                intent.putExtra("city", cityName);
                mMainActivity.startActivityForResult(intent, MainActivity.getResultForHomecity);
                break;
            case R.id.lay_netfailer:
                mProgress.setVisibility(View.VISIBLE);
                getData();
                break;
            case R.id.llay_home_findshop://找商家
                Intent intent2 = new Intent(mMainActivity, HomeFindbusinshopActivity.class);
                mMainActivity.startActivity(intent2);

                break;
            case R.id.llay_home_wedguid://结婚攻略 --> 电子请柬
                mActivity.startActivity(new Intent(mActivity, ElectronicInvitationHomeActivity.class));
                break;
            case R.id.llay_home_Einvitation:// 结婚游戏 跳转webview
                intent = new Intent(mMainActivity, WebViewActvity.class);
                intent.putExtra("urlPath", "http://j.66wedding.com/jht_game_index.html");
                intent.putExtra("title", "结婚小游戏");
                intent.putExtra("share", false);
                mMainActivity.startActivity(intent);
                break;
            case R.id.llay_home_freeExp:// 结婚趣闻 跳转webview
                intent = new Intent(mMainActivity, WebViewActvity.class);
                intent.putExtra("urlPath", "http://j.66wedding.com/news.html");
                intent.putExtra("title", "婚礼趣闻");
                intent.putExtra("share", true);
                mMainActivity.startActivity(intent);
                break;
            case R.id.rlay_home_hotel://酒店预订
                Intent intent3 = new Intent(mMainActivity, HomeHotelActivity2.class);
                intent3.putExtra("return", "首页");
                intent3.putExtra("title", "酒店预订");
                intent3.putExtra("categoryId", 1081);
                mMainActivity.startActivity(intent3);
                break;
            case R.id.rlay_home_wedshopping://婚品购置
                if (categuryData != null) {
                    Intent intent4 = new Intent(mMainActivity, HomeWedShoppingActivity.class);
                    Bundle bundle = new Bundle();
                    intent4.putExtra("return", "首页");
                    bundle.putSerializable("data", categuryData);
                    intent4.putExtra("title", "婚品购置");
                    intent4.putExtras(bundle);
                    mMainActivity.startActivity(intent4);
                }
                break;
            case R.id.rlay_home_wedphoto://蜜月旅拍
                Intent intent5 = new Intent(mMainActivity, HomeHotelActivity2.class);
                intent5.putExtra("return", "首页");
                intent5.putExtra("title", "蜜月旅拍");
                intent5.putExtra("categoryId", 1086);
                mMainActivity.startActivity(intent5);
                break;
            case R.id.rlay_home_celebrate://结婚婚庆
                Intent intent6 = new Intent(mMainActivity, HomeHotelActivity2.class);
                intent6.putExtra("return", "首页");
                intent6.putExtra("title", "结婚婚庆");
                intent6.putExtra("categoryId", 1082);
                mMainActivity.startActivity(intent6);
                break;
            case R.id.rlay_home_takephoto://婚纱摄影
                Intent intent7 = new Intent(mMainActivity, HomeHotelActivity2.class);
                intent7.putExtra("return", "首页");
                intent7.putExtra("title", "婚纱摄影");
                intent7.putExtra("categoryId", 1080);
                mMainActivity.startActivity(intent7);
                break;
            case R.id.iv_homepage_topicom://
                Intent intent8 = new Intent(mMainActivity, HomeHotelActivity2.class);
                intent8.putExtra("return", "首页");
                intent8.putExtra("title", "蜜月旅拍");
                intent8.putExtra("categoryId", 1086);
                mMainActivity.startActivity(intent8);
                break;
            case R.id.gotop_btn://到顶部
                mListView.setSelection(0);
                mGotopIv.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (pageIndex <= 1) {
            mRefreshView.stopRefresh();
        } else if (pageIndex > 1) {
            mRefreshView.stopLoadMore();
        }
        if (data instanceof HomeHeaderLooperBean) {//顶部广告轮播数据
            HomeHeaderLooperBean looperbean = (HomeHeaderLooperBean) data;
            looperDataList = looperbean.getData();
            setLooperView();//设置顶部的广告轮播
        } else if (data instanceof HomeBotomListBean) {//底部的List数据
            HomeBotomListBean bottomData = (HomeBotomListBean) data;
            switch (bottomData.getResCode()) {
                case "0000":
                    notifyViewLay(HAVEDATA);
                    if (isFirstRequest) {//第一次请求会用到这里
                        isFirstRequest = false;
                        bottomList = bottomData.getData();
                        if (bottomList != null) {
                            if (mHomeAdapter == null) {
                                mHomeAdapter = new HomeListAdapter();
                                mListView.setAdapter(mHomeAdapter);
                            }
                            mHomeAdapter.notifyDataSetChanged();
                            //这个也一定要调用不然，切换页面后导致浏览商品位置不是上次浏览位置，而是顶部
                            mListView.setSelection(mLastLoadIndex);
                            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    HomeBotomListBean.DataBean dataBean = bottomList.get(position - 1);
                                    mCurrentItem = position - 1;
                                    int i_id = dataBean.getI_Id();
                                    Intent intent = new Intent(mMainActivity, HomeProductdetailActivity.class);
                                    intent.putExtra("productId", i_id);
                                    mMainActivity.startActivity(intent);
                                }
                            });
                        }
                        pageIndex++;
                    } else if (pageIndex == 1) {//刷新会用到这里
                        pageIndex++;
                        bottomList.clear();
                        bottomList = bottomData.getData();
                        if (mHomeAdapter == null) {
                            mHomeAdapter = new HomeListAdapter();
                            mListView.setAdapter(mHomeAdapter);
                        }
                        mHomeAdapter.notifyDataSetChanged();
                    } else if (pageIndex > 1) {
                        pageIndex++;
                        List<HomeBotomListBean.DataBean> loadMoreData = bottomData.getData();
                        bottomList.addAll(loadMoreData);
                        if (mHomeAdapter != null) {
                            mHomeAdapter.notifyDataSetChanged();
                            mListView.setSelection(mLastLoadIndex);
                        }
                    }
                    break;
            }
        } else if (data instanceof CateguryGridViewBean) {
            categuryData = (CateguryGridViewBean) data;
        } else if (data instanceof MeShoppingCartDeleteBean) {      // 加入收藏成功后
            myDialog = new MyDialog(mActivity, "收藏成功!");
            myDialog.show();
            mhandler.sendEmptyMessageDelayed(DIALOG, 800);
            mHomeAdapter.notifyDataSetChanged();
        } else if (data instanceof CancelCollectBean) {      // 删除收藏成功后
            myDialog = new MyDialog(mActivity, "取消收藏成功!");
            myDialog.show();
            mhandler.sendEmptyMessageDelayed(DIALOG, 800);
            mHomeAdapter.notifyDataSetChanged();
        } else if (data instanceof HomeGifPathBean) {      // 获取首页gif图片
            HomeGifPathBean homeGifPathBean = (HomeGifPathBean) data;
            if (homeGifPathBean.getResCode() != null && homeGifPathBean.getResCode().equals("0000")) {
                homeGifBean = homeGifPathBean.getData();
                if (homeGifBean != null && homeGifBean.getImgUrl() != null)
                    saveGifPic(homeGifBean.getImgUrl());
            }
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {
        if (!MainActivity.isFirstIntoHome) {
            MainActivity.isFirstIntoHome = !MainActivity.isFirstIntoHome;
        }
        switch (errorBean.getErrorCode()) {
            case ErrorBean.NONET:
                notifyViewLay(NODATA);
                break;
            default:
                if (!isShowError) {
                    CUtils.showDataErrToast(mMainActivity);
                    isShowError = true;
                }
        }
    }

    class HomeListAdapter extends BaseAdapter {
        /**
         * 获取要显示的条目数
         */
        @Override
        public int getCount() {
            return bottomList == null ? 0 : bottomList.size();
        }

        /**
         * 得到当前position位置的item类型type
         */
        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return bottomList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final HomeBotomListBean.DataBean dataBean = bottomList.get(position);
            MyViewHolder holder;
            if (convertView == null) {
                holder = new MyViewHolder();
                convertView = View.inflate(mMainActivity, R.layout.item_home_businessshow, null);
                holder.mCollectRay = (RelativeLayout) convertView.findViewById(R.id.rl_me_collect);
                holder.mMarkimgIv = (ImageView) convertView.findViewById(R.id.iv_homebus_markimg);
                holder.mContentIv = (ImageView) convertView.findViewById(R.id.iv_homebusitem_business);
                holder.mCollectShowIv = (ImageView) convertView.findViewById(R.id.iv_home_collect_show);
                holder.mCollectNoIv = (ImageView) convertView.findViewById(R.id.iv_home_collect);
                holder.mStoreNameTv = (TextView) convertView.findViewById(R.id.tv_homebusitem_hotalname);
                holder.mItemPriceTv = (TextView) convertView.findViewById(R.id.tv_homelist_itemprice);
                holder.mItemMarketPriceTv = (TextView) convertView.findViewById(R.id.tv_homelist_itemmarketprice);
                holder.mItemMarketTv = (TextView) convertView.findViewById(R.id.tv_homecustom_talk);
                convertView.setTag(holder);
            } else {
                holder = (MyViewHolder) convertView.getTag();
            }
            String nvc_logoHttp = dataBean.getBusiness().getNvc_Logo();
            String nvc_picMainHttp = dataBean.getNvc_PicMain();
            String nvc_storeName = dataBean.getBusiness().getNvc_StoreName();
            final Boolean isCollect = dataBean.isIsCollection();
            islogin = ((GlobalApplication) mMainActivity.getApplication()).isLogin();
            if (islogin) {
                // 如果之前收藏过,则显示红心
                if (isCollect) {
                    holder.mCollectShowIv.setVisibility(View.VISIBLE);
                    holder.mCollectNoIv.setVisibility(View.GONE);
                } else {    // 如果没有收藏过就显示白心
                    holder.mCollectNoIv.setVisibility(View.VISIBLE);
                    holder.mCollectShowIv.setVisibility(View.GONE);
                }
            } else {
                holder.mCollectNoIv.setVisibility(View.VISIBLE);
                holder.mCollectShowIv.setVisibility(View.GONE);
            }
            x.image().bind(holder.mMarkimgIv, nvc_logoHttp, ImageOptionsUtil.getOptions92_92());
            Glide.with(mMainActivity).load(nvc_picMainHttp).error(R.mipmap.default_img).placeholder(R.mipmap.default_img).into(holder.mContentIv);
            holder.mStoreNameTv.setText(nvc_storeName);
            holder.mItemPriceTv.setText(String.valueOf(dataBean.getDm_ShopPrice()));
            holder.mItemMarketPriceTv.setText("¥" + String.valueOf(dataBean.getDm_Price()));
            holder.mItemMarketTv.setText(dataBean.getNvc_Name());
            holder.mItemMarketPriceTv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            holder.mCollectRay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    tempI_Id = dataBean.getI_Id();
                    tempI_Business = dataBean.getI_Business();
                    tempPosition = position;
                    islogin = ((GlobalApplication) mMainActivity.getApplication()).isLogin();
                    if (islogin) {
                        unCollectAndCollect();
                    } else {
                        showLoginDialog();
                    }
                }
            });
            return convertView;
        }

        class MyViewHolder {
            RelativeLayout mCollectRay;
            ImageView mMarkimgIv;
            ImageView mContentIv;
            TextView mStoreNameTv;
            TextView mItemPriceTv;
            TextView mItemMarketPriceTv;
            TextView mItemMarketTv;
            ImageView mCollectShowIv;
            ImageView mCollectNoIv;
        }
    }

    private void unCollectAndCollect() {
        HomeBotomListBean.DataBean dataBean = bottomList.get(tempPosition);
        if (dataBean.isIsCollection()) {        //如果收藏就取消收藏
            String oldUrl = UrlDealUtil.getRealUrlNewIdApi(RequestCode.POSTCOLLECTIONCANCEL);
            String url = oldUrl + "&productID=" + tempI_Id;
            HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                    HomePager.this, CancelCollectBean.class, RequestCode.POSTCOLLECTIONCANCEL);
            HttpHandleUtil.executeCommonPost(mActivity, httpRequestBean);
            dataBean.setIsCollection(false);
        } else {        // 如果没有收藏就收藏
            String oldUrl = UrlDealUtil.getRealUrlNewIdApi(RequestCode.POSTCOLLECTIONCREATE);
            String url = oldUrl + "&productID=" + tempI_Id + "&businessID=" + tempI_Business;
            HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                    HomePager.this, MeShoppingCartDeleteBean.class, RequestCode.POSTCOLLECTIONCREATE);
            HttpHandleUtil.executeCommonPost(mActivity, httpRequestBean);
            dataBean.setIsCollection(true);
        }
    }

    class ImgAdapter extends PagerAdapter {
        //设定Item数量
        @Override
        public int getCount() {
            return maxCount;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        /**
         * 初始化指定页视图对象
         * 1. 将指定下标对应的视图添加为container的子View
         * 2. 将视图返回
         */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            int index = position % looperDataList.size();
            String nvc_picMain = looperDataList.get(index).getNvc_PicMain();
            ImageView imgView = new ImageView(mMainActivity);
//            x.image().bind(imgView, nvc_picMain, ImageOptionsUtil.getOptions316_720());
            x.image().bind(imgView, nvc_picMain, ImageOptionsUtil.getOptions316_720_fixy());
            imgView.setTag(index);
            imgView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = (int) v.getTag();
                    int type = looperDataList.get(position).getBannerType();
                    Intent intent = null;
                    if (type == 1) {// 1表示商品 2表示广告
                        int i_id = looperDataList.get(position).getI_Id();
                        intent = new Intent(mMainActivity, HomeProductdetailActivity.class);
                        intent.putExtra("productId", i_id);
                        mMainActivity.startActivity(intent);
                    } else if (type == 2 && !TextUtils.isEmpty(looperDataList.get(position).getBannerUrl())) {
                        intent = new Intent(mMainActivity, WebViewActvity.class);
                        intent.putExtra("urlPath", looperDataList.get(position).getBannerUrl());
                        intent.putExtra("title", looperDataList.get(position).getNvc_Name());
                        intent.putExtra("share", false);
                        mMainActivity.startActivity(intent);
                    }
                }
            });

            if (imgView.getParent() == null) {
                container.addView(imgView, 0);
            } else {
                ((ViewGroup) imgView.getParent()).removeView(imgView);
                container.addView(imgView);
            }
            return imgView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
        }
    }

    Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TOPVIEWSCROLL:
                    int currentItem = mTopViewPager.getCurrentItem();
                    mTopViewPager.setCurrentItem(++currentItem);
                    mhandler.sendEmptyMessageDelayed(TOPVIEWSCROLL, 4000);
                    break;
                case DIALOG:
                    if (myDialog != null) {
                        myDialog.dismiss();
                    }
                    break;
                case MSG_INFRESH:
                    if (pageIndex == 1) {
                        mRefreshView.stopRefresh();
                    } else if (pageIndex > 1) {
                        mRefreshView.stopLoadMore();
                    }
                    break;
            }
        }
    };

    public void setLooperView() {
        MainActivity mainActivity = (MainActivity) ((GlobalApplication) mActivity.getApplication()).getMainActivityManager().getActivity("MainActivity");
        if (mainActivity != null) {
            mainActivity.isQuGuangguang = false;
        }
        mTopLooperLay.removeAllViews();
        if (looperDataList != null && looperDataList.size() > 0) {
            imgAdapter = new ImgAdapter();
            mTopViewPager.setAdapter(imgAdapter);
            int firstViewitem = maxCount / 2 - (maxCount / 2 % looperDataList.size());
            mTopViewPager.setCurrentItem(firstViewitem);
            mhandler.removeCallbacksAndMessages(null);
            mhandler.sendEmptyMessageDelayed(TOPVIEWSCROLL, 4000);
        }
        mPointList = new ArrayList<ImageView>();
        ImageView imageView = null;
        mPointList.clear();
        for (int i = 0; i < looperDataList.size(); i++) {
            imageView = new ImageView(mMainActivity);
            imageView.setBackgroundResource(R.drawable.splash_graypoint_shape);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DensityUtil.dip2px(6),
                    DensityUtil.dip2px(6));
            if (i != 0) {
                params.leftMargin = DensityUtil.dip2px(6);
            }
            mPointList.add(imageView);
            mTopLooperLay.addView(imageView, params);
        }

        mTopViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                position = position % looperDataList.size();
                float redpointdx = distance * (position + positionOffset);
                int disten = (looperDataList.size() - 1) * distance;
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(px, px);
                params.leftMargin = (int) redpointdx;
                if (redpointdx > disten) {
                    params.leftMargin = 0;
                }
                mRedpoint.setLayoutParams(params);
            }

            @Override
            public void onPageSelected(int position) {
                mCurrentItem = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                LogUtil.i("jiehuntong", "onPageScrollStateChanged：" + state);
                if (state == ViewPager.SCROLL_STATE_DRAGGING) {// 表示正在滑动
                    mRefreshView.setEnabled(false);
                    mhandler.removeCallbacksAndMessages(null);
                } else if (state == ViewPager.SCROLL_STATE_IDLE) {// 表示什么都没有做
                    mhandler.sendEmptyMessageDelayed(TOPVIEWSCROLL, 4000);
                } else if (state == ViewPager.SCROLL_STATE_SETTLING) {// 表示滑动完毕
                    mRefreshView.setEnabled(true);
                    mhandler.removeCallbacksAndMessages(null);
                }
            }
        });
    }

    //初始化上拉刷新
    private void initRefreshView() {
        //是否允许下拉刷新
        mRefreshView.setPullRefreshEnable(true);
        // 设置是否可以上拉加载
        mRefreshView.setPullLoadEnable(true);
        // 设置刷新完成以后，headerview固定的时间
        mRefreshView.setPinnedTime(1000);
        // 静默加载模式不能设置footerview
        // 设置支持自动刷新
        mRefreshView.setAutoLoadMore(false);

        mRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                pageIndex = 1;
                mLastLoadIndex = mListView.getLastVisiblePosition();
                mhandler.sendEmptyMessageDelayed(MSG_INFRESH, 5000);
                getDataFromNet(pageIndex);
            }

            @Override
            public void onLoadMore(boolean isSlience) {
                mLastLoadIndex = mListView.getLastVisiblePosition();
                mhandler.sendEmptyMessageDelayed(MSG_INFRESH, 5000);
                getDataFromNet(pageIndex);
            }
        });

        mRefreshView.setOnAbsListViewScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                mMainActivity.setmHomeCurrentItem(firstVisibleItem);
                mLastLoadIndex = firstVisibleItem;
                if (firstVisibleItem == 0) {
                    mGotopIv.setVisibility(View.GONE);
                } else if (firstVisibleItem > 10) {
                    mGotopIv.setVisibility(View.VISIBLE);
                }
            }
        });
    }


    public void notifyData() {
        super.notifyData();
        String cityName = mMainActivity.getCityName();
        mCitynameTv.setText(cityName);
    }

    public Handler getMhandler() {
        return mhandler;
    }

    private void notifyViewLay(int state) {
        switch (state) {
            case HAVEDATA:
                if (mRefreshView.isShown()) {
                    mGotopIv.setVisibility(View.GONE);
                    return;
                } else {
                    mRefreshView.setVisibility(View.VISIBLE);
                }
                mProgress.setVisibility(View.GONE);
                mNoDataLay.setVisibility(View.GONE);
                break;
            case NODATA:
                mProgress.setVisibility(View.GONE);
                mNoDataLay.setVisibility(View.VISIBLE);
                mRefreshView.setVisibility(View.GONE);
                mGotopIv.setVisibility(View.GONE);
                break;
            case DATAERROR:

                break;
        }
    }

    public void setPageIndex(int pageIndex) {
        HomePager.pageIndex = pageIndex;
    }

    /**
     * 自定义的对话框
     */
    class MyDialog extends Dialog {
        private String title;

        public MyDialog(Context context, String title) {
            super(context);
            this.title = title;
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //设置不显示对话框标题栏
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            //设置对话框显示哪个布局文件
            setContentView(R.layout.pop_tocollect);
            TextView titleTv = (TextView) findViewById(R.id.title);
            titleTv.setText(title);
        }
    }

    /**
     * 提示登录对话框
     */
    public void showLoginDialog() {
        final ConfirmLoginDialog confirmDialog = new ConfirmLoginDialog(mActivity, "亲，需要登录哦~", "去登录", "取消", R.layout.pop_tologin);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmLoginDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                Intent intent = new Intent(mActivity, LoginActivity.class);
                mActivity.startActivityForResult(intent, REQUEST_LOGIN_CODE);
                confirmDialog.dismiss();
            }

            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        islogin = ((GlobalApplication) mMainActivity.getApplication()).isLogin();
        User user = DataWareHourse.getInstance().getmUser();
        if (user != null) {
            i_id = user.getData().get(0).getI_Id();
        }
        mHomeAdapter.notifyDataSetChanged();//更新状态
        if (requestCode == REQUEST_LOGIN_CODE && resultCode == LoginActivity.LOGIN_OK) {
            unCollectAndCollect();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
